package controllers

import (
	"bsm/logger"
	"bsm/services"
	"net/http"
	"os"
	"path/filepath"
	"time"

	"github.com/gin-gonic/gin"
)

type ExportController interface {
	Export(ctx *gin.Context)
}

type exportControllerImpl struct {
	svcExport  services.ExportService
	svcConvert services.ConvertService
	svcAuth    services.AuthService
}

func NewExportController(export services.ExportService, convert services.ConvertService, auth services.AuthService) ExportController {
	return &exportControllerImpl{
		svcExport:  export,
		svcConvert: convert,
		svcAuth:    auth,
	}
}

func (c *exportControllerImpl) Export(ctx *gin.Context) {
	// 验证用户信息
	if !c.svcAuth.JWTAuthUser(ctx) {
		return
	}

	type exportReq struct {
		DesignCode string `json:"design_code"`
		DesignType int    `json:"design_type"`
	}
	var req exportReq
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"信息": "参数错误"})
		return
	}
	if req.DesignCode == "" {
		ctx.JSON(http.StatusBadRequest, gin.H{"信息": "项目编码为空"})
		return
	}
	if req.DesignType == 0 {
		ctx.JSON(http.StatusBadRequest, gin.H{"信息": "项目类型为空"})
		return
	}

	excelPath, err := c.svcExport.ExportProject(req.DesignCode, req.DesignType)

	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"信息": "导出失败"})
		return
	}

	pdfPath, err := c.svcConvert.ConvertExcelToPdf(excelPath)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"code": 1, "msg": "导出失败"})
		return
	}

	// 关键：设置 Content-Disposition 为 attachment
	ctx.Header("Cache-Control", "no-cache, no-store, must-revalidate")
	ctx.Header("Pragma", "no-cache")
	ctx.Header("Expires", "0")
	ctx.Header("Content-Transfer-Encoding", "binary")
	ctx.Header("Content-Disposition", "attachment; filename="+filepath.Base(pdfPath))
	ctx.Header("Content-Type", "application/pdf")

	// 发送文件
	ctx.File(pdfPath)

	// 异步删除文件
	go func() {
		time.Sleep(10 * time.Second)
		if _, err := os.Stat(pdfPath); err == nil {
			err = os.Remove(pdfPath)
			if err != nil {
				logger.WithFields(map[string]interface{}{
					"layer":     "controller",
					"operation": "exportController.Export",
				}).Errorf("删除PDF文件失败: %s", err.Error())
				return
			}
			// err = os.Remove(excelPath)
			// if err != nil {
			// 	logger.WithFields(map[string]interface{}{
			// 		"layer":     "controller",
			// 		"operation": "exportController.Export",
			// 	}).Errorf("删除Excel文件失败: %s", err.Error())
			// 	return
			// }
			logger.WithFields(map[string]interface{}{
				"layer":     "controller",
				"operation": "exportController.Export",
			}).Infof("已删除临时文件: %s, %s", pdfPath, excelPath)
		}
	}()
}
